package com.smsc.headend.connector.netty.initializer;

import cn.hutool.extra.spring.SpringUtil;
import com.smsc.headend.common.thread.UDISThreadFactory;
import com.smsc.headend.connector.netty.decoder.BytesInboundCounter;
import com.smsc.headend.connector.netty.decoder.DecodeProxy;
import com.smsc.headend.connector.netty.decoder.cosem.CosemByteDecoder;
import com.smsc.headend.connector.netty.encoder.CosemEncoder;
import com.smsc.headend.connector.netty.handler.BytesOutboundCounter;
import com.smsc.headend.connector.netty.handler.DLMSPacketHandler;
import com.smsc.headend.connector.service.DeviceConnectService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public class COSEMInitializer extends ChannelInitializer {
    @Autowired
    DeviceConnectService deviceConnectService;

    @Override
    protected void initChannel(Channel channel) throws Exception {
        CosemEncoder cosemEncoder = new CosemEncoder();
        DecodeProxy decodeProxy = new DecodeProxy();
        BytesInboundCounter bytesInboundCounter = new BytesInboundCounter();
        BytesOutboundCounter bytesOutboundCounter = new BytesOutboundCounter();
        CosemByteDecoder cosemByteDecoder = new CosemByteDecoder();
        DLMSPacketHandler handler = new DLMSPacketHandler();
        AutowireCapableBeanFactory autowireCapableBeanFactory = SpringUtil.getApplicationContext().getAutowireCapableBeanFactory();
        autowireCapableBeanFactory.autowireBean(cosemEncoder);
        autowireCapableBeanFactory.autowireBean(bytesInboundCounter);
        autowireCapableBeanFactory.autowireBean(bytesOutboundCounter);
        autowireCapableBeanFactory.autowireBean(handler);
        ChannelPipeline p = channel.pipeline();
        p.addLast("encoder", cosemEncoder);
        p.addLast("proxyDecoder", decodeProxy);
        p.addLast("bytesInBoundCounter", bytesInboundCounter);
        p.addLast("bytesOutboundCounter", bytesOutboundCounter);
        p.addLast("cosemDecoder", cosemByteDecoder);
        p.addLast(new IdleStateHandler(15, 15, 30), handler);
    }
}
